var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        var v = factory(require, exports);
        if (v !== undefined) module.exports = v;
    }
    else if (typeof define === "function" && define.amd) {
        define(["require", "exports", "react", "maishu-chitu", "maishu-chitu-react", "../../mobile/services/localService", "../../mobile/services/memberService", "maishu-jueying", "common", "../../mobile/error-handle", "json!websiteConfig"], factory);
    }
})(function (require, exports) {
    "use strict";
    var __syncRequire = typeof module === "object" && typeof module.exports === "object";
    Object.defineProperty(exports, "__esModule", { value: true });
    const React = require("react");
    const maishu_chitu_1 = require("maishu-chitu");
    const maishu_chitu_react_1 = require("maishu-chitu-react");
    const localService_1 = require("../../mobile/services/localService");
    const memberService_1 = require("../../mobile/services/memberService");
    const maishu_jueying_1 = require("maishu-jueying");
    const common_1 = require("common");
    const error_handle_1 = require("../../mobile/error-handle");
    const json_websiteConfig_1 = require("json!websiteConfig");
    function createService(type) {
        let service = new type();
        //TODO: 处理错误
        service.error.add((sender, error) => {
            // alert({ title: "错误", message: error.message });
            error_handle_1.errorHandle(error);
        });
        return service;
    }
    exports.createService = createService;
    let clientFiles = new maishu_chitu_1.ValueStore([]);
    let localService = createService(localService_1.LocalService);
    localService.clientFiles().then(value => {
        console.assert(value != null);
        clientFiles.value = value;
    });
    class BaseComponent extends React.Component {
        // componentCreated = Callbacks<BaseComponent<P, S>, React.Component<P, S>>();
        constructor(props) {
            super(props);
            let render = this.render;
            console.assert(render != null);
            this.render = () => {
                return React.createElement(maishu_jueying_1.MasterPageContext.Consumer, null, args => {
                    if (this.masterPage == null) {
                        this.masterPage = args.master;
                        this.memberService = this.createService(memberService_1.MemberService);
                        this.masterPage.getStyleColor().then(color => {
                            this.loadStyle(color);
                        });
                        this.masterPage.style.add(color => { this.loadStyle(color); });
                    }
                    console.assert(this.masterPage != null);
                    return React.createElement(maishu_chitu_react_1.PageContext.Consumer, null, args => {
                        if (args.page) {
                            this.app = args.page.app;
                            this.page = args.page;
                        }
                        return render.apply(this);
                    });
                });
            };
        }
        getComponentPaths() {
            return __awaiter(this, void 0, void 0, function* () {
                if (BaseComponent.componentInfos != null && BaseComponent.componentInfos.length > 0)
                    return BaseComponent.componentInfos;
                BaseComponent.componentInfos = yield localService.getComponentInfos();
                return BaseComponent.componentInfos;
            });
        }
        get isRuntime() {
            return window[common_1.ADMIN_APP] == null;
        }
        static get isDesigntime() {
            return window[common_1.ADMIN_APP] != null;
        }
        createService(type) {
            return createService(type);
        }
        loadStyle(color) {
            return __awaiter(this, void 0, void 0, function* () {
                color = color || "default";
                // clientFiles.attach(async (files) => {
                let files = clientFiles.value;
                let componentPaths = yield this.getComponentPaths();
                let componentPath = componentPaths.filter(o => o.name == this.constructor.name)[0];
                console.assert(componentPath != null);
                let path = componentPath.path;
                if (path.endsWith(".js")) {
                    path = path.substr(0, path.length - 3);
                }
                let lessPath = `${path}.less`;
                if (files.indexOf(lessPath) >= 0) {
                    BaseComponent.loadLessFile(this, color, lessPath);
                }
                // })
            });
        }
        static loadLessFile(componentOrName, color, path) {
            return __awaiter(this, void 0, void 0, function* () {
                color = color == null ? "default" : color;
                var typeName;
                if (typeof componentOrName == "string") {
                    typeName = componentOrName;
                }
                else {
                    typeName = componentOrName.constructor.name;
                    typeName = typeName.replace('Control', '');
                    typeName = typeName[0].toLowerCase() + typeName.substr(1);
                }
                let styleAttrName = "data-name";
                let style = document.head.querySelector(`style[${styleAttrName}="${typeName}"]`);
                if (!style) {
                    style = document.createElement('style');
                    style.type = 'text/css';
                    style.setAttribute(styleAttrName, typeName);
                    document.head.appendChild(style);
                }
                if (color == style.getAttribute('color')) {
                    return;
                }
                style.setAttribute('color', color);
                let contexts = requirejs.exec("contexts");
                let context = contexts[json_websiteConfig_1.contextName];
                if (context != null && context.config.baseUrl != null) {
                    path = context.config.baseUrl + path;
                }
                let lessText;
                lessText = `@import "${path}";`;
                if (color != 'default') {
                    if (context != null && context.config.baseUrl != null)
                        lessText = lessText + `@import "${context.config.baseUrl}components/style/colors/${color}.less";`;
                    else
                        lessText = lessText + `@import "components/style/colors/${color}.less";`;
                }
                (__syncRequire ? Promise.resolve().then(() => require("lessc")) : new Promise((resolve_1, reject_1) => { require(["lessc"], resolve_1, reject_1); })).then(lessc => {
                    let parser = new lessc.Parser(window['less']);
                    parser.parse(lessText, (err, tree) => {
                        if (err) {
                            console.error(err);
                            return;
                        }
                        style.innerHTML = tree.toCSS();
                    });
                });
            });
        }
    }
    exports.BaseComponent = BaseComponent;
});
